﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace CCF20Model
{
    public class FaultModel
    {
        CCF20Entities ccf20Entities;
        public FaultModel()
        {
            ccf20Entities = new CCF20Entities();
            
        }
        public DateTime GetLastCrashTime()
        {
            Fault lastCrash = ccf20Entities.Faults.Where(f => f.FaultType == "撞车").OrderByDescending(f => f.HappenDate).FirstOrDefault();
            if (lastCrash != null)
            {
                return lastCrash.HappenDate;
            }
            else
            {
                //if there is not crash data before. then try from last 24 hours.
                return new DateTime(2011, 1, 1);
                //return (DateTime.Now - new TimeSpan(24, 0, 0));
            }
        }
        public Vehicle GetVehicleBySimNumber(Fault f)
        {
            Vehicle vehicle = ccf20Entities.Vehicles.Where(v => v.Devices.Count(d => d.IDCSimNumber == f.IDCSimNumber && d.IsRegistered ==true) == 1).FirstOrDefault();
            if (vehicle == null)
            {
                f.IsActive = false;
                f.IsConfirmed = false;
                f.CloseReason = "未找到车辆";
                LoggerHelper.LogZICDebug(f, string.Format("没有找到SIM卡号为{0},并且已经注册成功的车辆", f.IDCSimNumber));
                return null;
            }
            else
            {
                return vehicle;
            }
        }
        public int GetAnchiID()
        {
            int? maxID = ccf20Entities.Faults.Where(f => f.FaultType == "故障").Max(f => f.AnchiID);
            if (maxID == null)
            {
                return 0;
            }
            else
            {
                return (int)maxID;
            }

        }

        public bool CheckPriorityAndCustomizedCode(Fault fault, Vehicle vehicle)
        {
            //判断故障码是否相同，还要看车型
            CustomizedTroubleCode customizedCode = ccf20Entities.CustomizedTroubleCodes.Where(f => f.Code == fault.Code && f.VehicleTypeID == vehicle.VehicleTypeID).FirstOrDefault();

            if (customizedCode != null)
            {
                //在个性化故障码库中，我们只取等级 <4的故障码,忽略故障等级>=4的故障 
                if (customizedCode.Priority >= 4)
                {
                    fault.IsActive = false;
                    fault.CloseDate = DateTime.Now;
                    fault.CloseReason = "不重要故障";
                    LoggerHelper.LogZICDebug(fault, "在个性化故障码库中的已确认要排除的偶发故障");
                    return false;
                }
                else
                {
                    //在用个性化故障码库中的代码描述来取代智信通的故障描述，
                    fault.CodeDescription = customizedCode.CodeDescription;
                    fault.Priority = customizedCode.Priority;
                    fault.IsConfirmed = true;
                    fault.CloseReason = "需要处理";
                    LoggerHelper.LogZICDebug(fault, "个性化故障码库中的直通车故障");
                }
            }
            else
            {
                //凡是不在个性化故障码库的故障，都需要经过2模块确定，才到客户关怀模块
                fault.IsConfirmed = false;
                fault.CloseReason = "需要处理";
                LoggerHelper.LogZICDebug(fault, "不在个性化故障码库中-非直通车-需要2模块确认");
                
            }
            return true;
        }
        public bool IsRegisteredVehicle(Fault fault, Vehicle vehicle)
        {
            Vehicle myVehicle = ccf20Entities.Vehicles.Where(v => v.VehicleID == vehicle.VehicleID).FirstOrDefault();
            Device device = myVehicle.Devices.FirstOrDefault();
            if (device.IsRegistered != null && device.IsRegistered == true)
            {
                return true;
            }
            else
            {
                fault.IsActive = false;
                fault.CloseDate = DateTime.Now;
                fault.CloseReason = "未注册";
                LoggerHelper.LogZICDebug(fault, null);
                //ccf20Entities.Faults.AddObject(fault);
                //ccf20Entities.SaveChanges();
                return false;
            }

        }
        public bool IsDuplicateFault(Fault fault, Vehicle vehicle)
        {
            Fault currentFault = null;
            if (fault.FaultType == "故障")
            {
                //对于相同的车辆的同一个故障，视为重复
                currentFault = ccf20Entities.Faults.Where(f => f.IsActive && f.VehicleID == vehicle.VehicleID && f.Code == fault.Code).FirstOrDefault();
                if (currentFault != null)
                {
                    fault.IsActive = false;
                    fault.CloseReason = "重复故障";
                    LoggerHelper.LogZICDebug(fault, "对于同一车辆的有一个相同的还未处理的故障-视为重复");
                }
            }
            else if (fault.FaultType == "撞车")
            {
                //对于撞车,同一辆车多个撞车，只取最后一个
                currentFault = ccf20Entities.Faults.Where(f => f.IsActive && f.VehicleID == vehicle.VehicleID && f.FaultType == "撞车").FirstOrDefault();
                if (currentFault != null)
                {
                    fault.IsActive = false;
                    fault.CloseReason = "重复撞车";
                    LoggerHelper.LogZICDebug(fault, "对于同一车辆有多于一个的还未处理的撞车-视为重复");
                }
            }
            else if (fault.FaultType == "里程")
            {
                //对于撞车和里程，对于相同的车辆,相同的里程，视为重复
                currentFault = ccf20Entities.Faults.Where(f => f.IsActive && f.VehicleID == vehicle.VehicleID && f.CurrentMileage == fault.CurrentMileage).FirstOrDefault();
                if (currentFault != null)
                {
                    fault.IsActive = false;
                    fault.CloseReason = "重复里程";
                    LoggerHelper.LogZICDebug(fault, "对于同一车辆有多于一个相同的里程-视为重复");
                    
                }
            }
            if (currentFault != null)
            {
                //如果是重复的故障码，我们要跟新现有的FAULTID，避免重复取之
                if (currentFault.AnchiID < fault.AnchiID)
                {
                    currentFault.AnchiID = fault.AnchiID;
                    currentFault.HappenDate = fault.HappenDate;
                    ccf20Entities.SaveChanges();
                }
                return true; //if we get the fault already, then do nothing.
            }
            else
            {
                return false;
            }

        }

        public Vehicle GetValidVehicleByFault(Fault fault)
        {

            //根据IDC号取得客户，如果无法找到客户，则报错。 ZIC送错IDC
            Vehicle vehicle = GetVehicleBySimNumber(fault);

            if (vehicle == null) return null;

            //故障码，里程码都带有最新车辆里程信息
            if (fault.CurrentMileage != null)
            {
                vehicle.CurrentMileage = fault.CurrentMileage;
            }
            
            //如果该车辆的上次服务里程和时间为空，则用当前里程和时间初始化,(包括车辆的维护项目）
            if (vehicle.LastServiceMileage == null || vehicle.LastServcieDate == null)
            {
                if (fault.CurrentMileage != null)
                {
                    vehicle.LastServiceMileage = fault.CurrentMileage;
                    vehicle.LastServcieDate = DateTime.Now;
                    LoggerHelper.LogZICMonitor(string.Format(@"车牌为:{0}的车辆的上次服务里程和时间还未初始化,以收到的故障码:{1} 的当前里程:{2}和时间初始化",
                                                                vehicle.VehicleLicense,
                                                                fault.Code,
                                                                fault.CurrentMileage));

                    foreach (VehicleMaintenanceRecord vmr in vehicle.VehicleMaintenanceRecords)
                    {
                        if (vmr.MaintenanceType == null)
                        {
                            LoggerHelper.LogZICMonitor(string.Format(@"车牌为:{0} ID为:{1}的车辆的维护记录中维护项目为空",
                                                vehicle.VehicleLicense,
                                                vehicle.VehicleID));

                            continue;
                        }
                        vmr.LastServiceMileage = vehicle.CurrentMileage;
                        vmr.LastServiceDate = DateTime.Now;
                        LoggerHelper.LogZICMonitor(string.Format(@"保养记录:{0} 还未初始化上次服务时间和里程，以收到的故障码:{1} 的当前里程:{2}和时间初始化",
                                                                        vmr.MaintenanceType.Name,
                                                                        fault.Code,
                                                                        fault.CurrentMileage));
                    }
                }
            }
            
            //保存对车辆的更新
            ccf20Entities.SaveChanges();
            
            fault.VehicleID = vehicle.VehicleID;
            
            //判断客户是否有联系标记
            if (vehicle.LastContactResult != null)
            {
                if (vehicle.LastContactResult == Enum.GetName(typeof(EnumContactResult), EnumContactResult.放弃客户))
                {
                    //如果放弃用户，则屏蔽所有请求包括撞车
                    fault.IsActive = false;
                    fault.CloseDate = DateTime.Now;
                    fault.CloseReason = vehicle.LastContactResult;
                    LoggerHelper.LogZICDebug(fault, "放弃客户-屏蔽所有请求包括撞车");
                    return null;
                }

                //忽略还未决定客户,处于联系中的客户不在显示新的故障，保养
                //忽略同意回场客户,处于联系中的客户不在显示新的故障，保养
                //忽略实际回场客户,处于联系中的客户不在显示新的故障，保养
                //忽略被放弃客户
                if (vehicle.LastContactResult == Enum.GetName(typeof(EnumContactResult), EnumContactResult.联络上同意回场) ||
                    vehicle.LastContactResult == Enum.GetName(typeof(EnumContactResult), EnumContactResult.联络上还未决定) ||
                    vehicle.LastContactResult == Enum.GetName(typeof(EnumContactResult), EnumContactResult.客户实际回场)
                    )
                {
                    if (fault.FaultType != Enum.GetName(typeof(EnumFaultType), EnumFaultType.撞车))
                    {
                        //如果是撞车，   即使客户已经处于联系中，也显示撞车请求

                        fault.IsActive = false;
                        fault.CloseDate = DateTime.Now;
                        fault.CloseReason = vehicle.LastContactResult;
                        LoggerHelper.LogZICDebug(fault, "客户已处于联系中-而且不是撞车请求-屏蔽新的故障码");
                        return null;
                    }
                    LoggerHelper.LogZICDebug(fault, string.Format("客户已处于联系中-{0}-但这是撞车请求-不屏蔽",vehicle.LastContactResult));
                }
                else if ((vehicle.LastContactResult.Contains("拒绝") && (DateTime.Now - new TimeSpan(30, 0, 0, 0)) < vehicle.LastContactTime))
                {

                    if (fault.FaultType == Enum.GetName(typeof(EnumFaultType), EnumFaultType.撞车))
                    {
                        //如果是撞车，要判断当他上次拒绝时，是否有撞车的请求。 如果有，则一起屏蔽撞车，如果没有，则不屏蔽撞车
                        VehicleRepairHistory vrh = vehicle.VehicleRepairHistories.OrderByDescending(r => r.InShopDate).FirstOrDefault();
                        Fault crashfault = vrh.Faults.Where(f => f.FaultType == "撞车").FirstOrDefault();
                        if (crashfault != null)
                        {
                            fault.IsActive = false;
                            fault.IsConfirmed = false;
                            fault.CloseDate = DateTime.Now;
                            fault.CloseReason = vehicle.LastContactResult;
                            LoggerHelper.LogZICDebug(fault, "拒绝客户-客户上次拒绝时间小于30天-上次拒绝时包括撞车-所以在30天内不显示撞车请求");
                            return null;
                        }
                        LoggerHelper.LogZICDebug(fault, "拒绝客户-客户上次拒绝时间小于30天-上次拒绝时不包括撞车-所以显示这次撞车请求");
                    }
                    else
                    {
                        //忽略在过去三十天内，拒绝回场的用户的故障请求，里程（保养）,
                        fault.IsActive = false;
                        fault.IsConfirmed = false;
                        fault.CloseDate = DateTime.Now;
                        fault.CloseReason = vehicle.LastContactResult;
                        LoggerHelper.LogZICDebug(fault, "拒绝客户-而且客户上次拒绝时间小于30天-所以在30天内不显示故障维修请求");
                        return null;
                    }
                }
                
            }
            return vehicle;
        }
        public void CreateNewMaintenance(Fault fault,Vehicle vehicle)
        {
            
            //VehicleMaintenanceModel vmm = new VehicleMaintenanceModel();
            //vmm.AddDefaultMaintenanceToVehicle(vehicle);


            //在任何情况下，车辆的当前里程都来自上位机上传的实际里程信息
            //虚拟里程，只应用于当用户拒绝回场或放弃时，就用车辆的当时里程和时间替代上次服务里程和时间
            if ((fault.CurrentMileage != null) && (fault.CurrentMileage != 0))
            {
                vehicle.CurrentMileage = fault.CurrentMileage;
            }

            // 如果对于同一个保养项目有多个记录，说明是不同次数的保养,取最小的还未做过的一个
            var myMaintenanceGroup = from vmr in vehicle.VehicleMaintenanceRecords
                                      where vmr.IsActive &&
                                            vmr.VehicleID == vehicle.VehicleID
                                      group vmr by vmr.AnchiID into fullPriority
                                      let minPriority = fullPriority.Min(f=>f.Priority)
                                      select new 
                                      {
                                          AnchiID = fullPriority.Key,
                                          MinPriorityService = fullPriority.Where(f=>f.Priority == minPriority),
                                          //为了把上次服务记录，传给次数更高的保养项目，要取至少两条记录
                                          // 我们在客户出场时把上次服务记录，传给次数更高的保养项目
                                          //MinPriorityService = fullPriority.OrderBy(f=>f.Priority).Take(2),
                                          RecordCount = fullPriority.Count()
                                      };
            
            foreach (var g in myMaintenanceGroup)
            {
                VehicleMaintenanceRecord vmr = g.MinPriorityService.First();
                //验证是否已经有相同的保养请求存在
                VehicleMaintenanceHistory vmh = ccf20Entities.VehicleMaintenanceHistories.Where(
                                                    m=>m.IsActive &&
                                                       m.VehicleID == vehicle.VehicleID && 
                                                       m.MaintenanceTypeID == vmr.MaintenanceTypeID &&
                                                       m.Priority == vmr.Priority)
                                                       .FirstOrDefault();
                LoggerHelper.LogZICMonitor(string.Format("保养项目={0},保养里程={1},保养周期={2},次数={3},当前里程={4}，上次服务里程={5}，上次服务时间={6}",
                                                            vmr.MaintenanceType.Name,
                                                            vmr.ServiceMileage,
                                                            vmr.ServicePeriod,
                                                            vmr.Priority,
                                                            fault.CurrentMileage,
                                                            vmr.LastServiceMileage,
                                                            vmr.LastServiceDate));
                if (vmh != null) continue;

                // 车辆应该已经在GetValidVehicleByFault里初始化 维护项目上次服务时间和里程
                // Just in case 如果车辆没有初始化上次服务时间和里程，则以当前车程和当日时间作为初始化时间
                if ((vmr.LastServiceMileage == null) || (vmr.LastServiceDate == null))
                {
                    vmr.LastServiceMileage = vmr.LastServiceMileage ?? vehicle.CurrentMileage;
                    vmr.LastServiceDate = vmr.LastServiceDate ?? DateTime.Now;

                    LoggerHelper.LogZICMonitor(string.Format("BUG BUG 车辆车牌:{0}的维护项目:{1}不应该没有初始化上次服务时间和里程",
                                                                    vehicle.VehicleLicense,
                                                                    vmr.MaintenanceType.Name));


                }

                if (fault.CurrentMileage != null)
                {
                    vmr.CurrentMileage = fault.CurrentMileage;

                    //L2-L0+500>L
                    //T2-T0-15>T

                    if (
                        (vmr.ServiceMileage != null && 
                         fault.CurrentMileage - vmr.LastServiceMileage + 500 > vmr.ServiceMileage)
                         ||
                        (vmr.ServicePeriod != null &&
                         DateTime.Now - new TimeSpan(15, 0, 0, 0) - new TimeSpan((int)vmr.ServicePeriod, 0, 0, 0)> vmr.LastServiceDate)
                        )
                    {
                        vehicle.IsMaintenance = true;
                        vehicle.IsActive = true;
                        vehicle.LatestActiveTime = DateTime.Now;
                        //if (g.RecordCount > 1)
                        //{
                        //    //如果对于同一个保养项目有多个记录，说明是不同次数的保养
                        //    // 但是我们只有在出场时才把这个保养项目取消
                        //    vmr.IsActive = false;
                        //}
                        vmh = new VehicleMaintenanceHistory();
                        vmh.ReceiveDate = DateTime.Now;
                        vmh.HappenDate = fault.HappenDate;
                        vmh.EffectiveReceiveDate = fault.EffectiveReceiveDate;
                        vmh.VehicleID = vmr.VehicleID;
                        vmh.MaintenanceTypeID = vmr.MaintenanceTypeID;
                        vmh.LastServiceDate = vmr.LastServiceDate;
                        vmh.LastServiceMileage = vmr.LastServiceMileage;
                        vmh.CurrentMileage = vehicle.CurrentMileage;
                        vmh.IsActive = true;
                        vmh.Priority = vmr.Priority;
                        ccf20Entities.VehicleMaintenanceHistories.AddObject(vmh);
                    }
                    else
                    {
                        //如果ServiceMileage和ServicePeriod没有定义，则不会产生保养需求。
                        LoggerHelper.LogZICMonitor(string.Format(@"未产生保养需求 IDCSimNumber={3} 车辆ID={4} 故障码={0} Desc={1} CurrentMileage={2}",
                                                                    fault.Code,
                                                                    fault.CodeDescription,
                                                                    fault.CurrentMileage,
                                                                    fault.IDCSimNumber,
                                                                    fault.VehicleID));
                    }
                }

            }
            ccf20Entities.SaveChanges();
        }
        public void GetCustomizedCode(Fault fault)
        {
            CustomizedTroubleCode customizedCode = ccf20Entities.CustomizedTroubleCodes.Where(c => c.Code == fault.Code).FirstOrDefault();
            if (customizedCode != null)
            {
                fault.CodeDescription = customizedCode.CodeDescription;
            }
        }
        public bool CheckFault(Fault fault,out Vehicle vehicle)
        {
            vehicle = GetValidVehicleByFault(fault);
            if (vehicle == null)
            {
                return false;
            }
            else if (IsDuplicateFault(fault, vehicle))
            {
                //判断在当前接收到的故障码中，是否有重复的故障码
                //当CCF 向 ZIC 取故障码时，如果输入不同步的MAXID，就会造成同一条故障码被接受两次
                //这包括任何的故障码，包括故障，撞车，里程
                //如果是重复的故障码，我们要跟新现有的FAULTID，避免重复取之

                
            
                return false;
            }
            else
            {
                return true;
            }

        }
        public void CreateNewFault(Fault fault,Vehicle vehicle)
        {

            //判断在当前接收到的故障码是否有相应的车辆，车辆的状态是否要求相应故障码
            
            fault.VehicleID = vehicle.VehicleID;
            if (fault.FaultType == "撞车")
            {
                vehicle.IsUrgent = true;
                fault.CloseReason = "需要处理";
                LoggerHelper.LogZICDebug(fault, null);    

            }
            else if (fault.FaultType == "故障")
            {

                //1. 判断是否故障码是否在4S店个性化码库里，如果有的话，就采用故障码的个性化描述,个性化等级
                //2.  判断故障码等级 1～3 直通车， 4～ 需要确认/直接忽略
                if (!CheckPriorityAndCustomizedCode(fault, vehicle)) return;
                vehicle.IsFault = true;

            }
            
            vehicle.IsActive = true;
            vehicle.LatestActiveTime = DateTime.Now;
            vehicle.LastContactResult = Enum.GetName(typeof(EnumContactResult), EnumContactResult.未联系);
            ccf20Entities.Faults.AddObject(fault);
            ccf20Entities.SaveChanges();

        }
        public void AddDirectTroubleCode(Fault skipCode)
        {
            CustomizedTroubleCode ctc = ccf20Entities.CustomizedTroubleCodes.Where(c => c.Code == skipCode.Code && c.CodeVersion == skipCode.CodeVersion).FirstOrDefault();
            if (ctc == null)
            {
                ctc = new CustomizedTroubleCode();
                ccf20Entities.CustomizedTroubleCodes.AddObject(ctc);
            }
            ctc.Code = skipCode.Code;
            ctc.CodeDescription = skipCode.CodeDescription;
            ctc.CodeVersion = skipCode.CodeVersion;
            //ctc.CodeType = skipCode.CodeType;
            ctc.CodeType = "直通车";
            //直通车的等级>4
            ctc.Priority = 1;
            ctc.IsCustomized = true;
            Vehicle vehicle = ccf20Entities.Vehicles.Where(v => v.VehicleID == skipCode.VehicleID).FirstOrDefault();
            if (vehicle != null)
            {
                ctc.VehicleType = vehicle.VehicleType;
            }
            else
            {
                throw new Exception("Can't find the vehicle based on fault");
            }
            Fault myFault = ccf20Entities.Faults.Where(f => f.FaultID == skipCode.FaultID).FirstOrDefault();
            if (myFault != null)
            {
                myFault.IsConfirmed = true;
                LoggerHelper.LogCCF20(string.Format("将故障码{0} 车型{1}-{2}-{3} 设置为直通车",
                                                myFault.Code,
                                                vehicle.VehicleType.Manufacture,
                                                vehicle.VehicleType.Model,
                                                vehicle.VehicleType.EngineType));

            }
            ccf20Entities.SaveChanges();

        }
        public void AddSkipTroubleCode(Fault skipCode)
        {
            CustomizedTroubleCode ctc = ccf20Entities.CustomizedTroubleCodes.Where(c => c.Code == skipCode.Code && c.CodeVersion == skipCode.CodeVersion).FirstOrDefault();
            if (ctc == null)
            {
                ctc = new CustomizedTroubleCode();
                ccf20Entities.CustomizedTroubleCodes.AddObject(ctc);
            }
            ctc.Code = skipCode.Code;
            ctc.CodeDescription = skipCode.CodeDescription;
            ctc.CodeVersion = skipCode.CodeVersion;
            ctc.CodeType = "排除";
            ctc.Priority = 5;
            ctc.IsCustomized = true;
            Vehicle vehicle = ccf20Entities.Vehicles.Where(v => v.VehicleID == skipCode.VehicleID).FirstOrDefault();
            if (vehicle != null)
            {
                ctc.VehicleType = vehicle.VehicleType;
            }
            else
            {
                throw new Exception("Can't find the vehicle based on fault");
            }
            Fault myFault = ccf20Entities.Faults.Where(f => f.FaultID == skipCode.FaultID).FirstOrDefault();
            if (myFault != null)
            {
                myFault.IsActive = false;
                myFault.CloseDate = DateTime.Now;
                myFault.CloseReason = "人工排除";
                
            }
            ccf20Entities.SaveChanges();
        }
        public void ConfirmTroubleCode(Fault confirmCode)
        {
            Fault fault = ccf20Entities.Faults.Where(f => f.FaultID == confirmCode.FaultID).FirstOrDefault();
            if (fault != null)
            {
                fault.IsConfirmed = true;
                fault.CloseReason = "已经确认";
                ccf20Entities.SaveChanges();
            }
        }
        public string GetZICUrl()
        {
            CompanyProfile profile = ccf20Entities.CompanyProfiles.FirstOrDefault();
            string url;
            if (profile != null)
            {
                url = profile.ZICUrl;
            }
            else
            {
                url = "http://218.249.201.46:8899/zic/zicwebservice.asmx";
            }
            //EndpointAddress endpoint;
            //try
            //{
            //    endpoint = new EndpointAddress(url);
            //}
            //catch (Exception ex)
            //{
            //    endpoint = new EndpointAddress("http://218.249.201.46:8899/zic/zicwebservice.asmx");
            //}
            return url;
        }
        public void UpdateZICInfo(DateTime lastAccessTime,bool IsAvailable)
        {
            CompanyProfile profile = ccf20Entities.CompanyProfiles.FirstOrDefault();
            profile.ZICAvailable = IsAvailable;
            if (IsAvailable)
            {
                profile.ZICUpdateTime = lastAccessTime;
            }
            ccf20Entities.SaveChanges();
            
        }
        public void GetZICInfo(out DateTime lastAccessTime, out bool IsAvailable)
        {
            CompanyProfile profile = ccf20Entities.CompanyProfiles.FirstOrDefault();
            IsAvailable = profile.ZICAvailable ?? true ;
            lastAccessTime = profile.ZICUpdateTime ?? DateTime.Now ;
        }
        public LoginInfo GetLoginInfo()
        {
            CompanyProfile profile = ccf20Entities.CompanyProfiles.FirstOrDefault();
            LoginInfo login = new LoginInfo();
            if (profile != null)
            {
                login.IDSName = profile.LoginName;
                login.IDSPassword = profile.LoginPassword;
            }
            else
            {
                login.IDSName = "5";
                login.IDSPassword = "1";
            }
            return login;
        }

        public void CustomizeCodeDescription(int vehicleID,string newValue,Fault fault )
        {
            Vehicle vehicle = ccf20Entities.Vehicles.Where(v => v.VehicleID == vehicleID).FirstOrDefault();
            if (vehicle == null) return;

            CustomizedTroubleCode ctc = ccf20Entities.CustomizedTroubleCodes.Where(c => c.Code == fault.Code && c.VehicleTypeID == vehicle.VehicleTypeID).FirstOrDefault();
            if (ctc == null)
            {
                ctc = new CustomizedTroubleCode();
                ccf20Entities.CustomizedTroubleCodes.AddObject(ctc);
                ctc.Code = fault.Code;
                ctc.Priority = fault.Priority;
                ctc.CodeVersion = fault.CodeVersion;
                ctc.CodeType = fault.CodeType;
                ctc.IsCustomized = true;
                ctc.VehicleTypeID = vehicle.VehicleTypeID;

            }
            ctc.CodeDescription = newValue;
            ccf20Entities.SaveChanges();

        }
        public void CustomizeCodePriority(int vehicleID, int newValue, Fault fault)
        {
            Vehicle vehicle = ccf20Entities.Vehicles.Where(v => v.VehicleID == vehicleID).FirstOrDefault();
            if (vehicle == null) return;

            CustomizedTroubleCode ctc = ccf20Entities.CustomizedTroubleCodes.Where(c => c.Code == fault.Code && c.VehicleTypeID == vehicle.VehicleTypeID).FirstOrDefault();
            if (ctc == null)
            {
                ctc = new CustomizedTroubleCode();
                ccf20Entities.CustomizedTroubleCodes.AddObject(ctc);
                ctc.Code = fault.Code;
                ctc.CodeDescription = fault.CodeDescription;    
                ctc.CodeVersion = fault.CodeVersion;
                ctc.CodeType = fault.CodeType;
                ctc.IsCustomized = true;
                ctc.VehicleTypeID = vehicle.VehicleTypeID;

            }
            ctc.Priority = (short)newValue;
            ccf20Entities.SaveChanges();

        }
        public IQueryable<Fault> GetFaultQuery()
        {
            var query = from f in ccf20Entities.Faults
                        orderby f.HappenDate descending
                        select f;
            return query;
        }
        public IQueryable<VehicleMaintenanceHistory> GetMaintenanceQuery()
        {
            var query = from m in ccf20Entities.VehicleMaintenanceHistories
                        orderby m.CloseDate descending
                        select m;
            return query;
        }
    }

    public class LoginInfo
    {
        public string IDSName { get; set; }
        public string IDSPassword { get; set; }
    }
    
}
